import { GameData } from "./GameData";
import { JsbTileTrileTileCallMgr } from "./JsbMgr";
import LanguagetileTile from "./Language";
import UITileToast from "./UIToast";
import Archive from "../Common/Archive";
import CCLog from "../CCLog";
import GameTileStaticData, { videoSceneType } from "../GameStaticData";
import getEventEmiter from "../Libraries/EventEmitter";
import { CUSTOM_EVENT_NAME } from "./Constant";
import GameTileStaticJsonData from "../GameStaticJsonData";
const videoInterval=5;//视频播放间隔时间
let closeWindowCount = 0;
let  lastShowVideoSecond=0;
export const showVideoAd = (sceneTyep = videoSceneType.videoScene_none) : Promise<string> =>{
    return new Promise((reslove, reject) => {
        let nowSecond=Math.floor(new Date().getTime()/1000);
        let interval=nowSecond-lastShowVideoSecond;
        if(interval<videoInterval){
            UITileToast.popUp(LanguagetileTile.getWord("ADTooPFxSRetry",videoInterval-interval))
            reject();
            return;
        }

        window.onAdShow = (plantFromId:number) => {
            window.onAdShow = null;
        }

        window.onAdClose = (plantFromId:number,result : string) => {
            lastShowVideoSecond=nowSecond;
            window.onAdClose = null;
            window.onAdError = null;
            try{
                Archive.checkTask(2);
                if (result){
                    reslove(result);
                }else{
                    reslove(null);
                }
            }catch{
            }
        }
        
        window.onAdError = (adErrorMsg:string) =>{
            window.onAdError = null;
            window.onAdClose = null;
            window.onAdShow = null;
            if(adErrorMsg == "1113" ){//add/video  获取奖励失败，请完整播放广告
                UITileToast.popUp("获取奖励失败,请完整播放广告");
            }else if (adErrorMsg && adErrorMsg.indexOf("10005") != -1) {//10005,任务未完成: 中途退出

            }  else if ("frequently" === adErrorMsg) {
                //原生返回的太频繁提示
            } else {
                getEventEmiter().emit(CUSTOM_EVENT_NAME.videoPlayFailed);
                UITileToast.popUp(LanguagetileTile.getWord("ADNotLoadPlayerLaterRetry"));
            }
            reject()
        }
        GameTileStaticData.videoScene = sceneTyep
        JsbTileTrileTileCallMgr.handler('showVideoAd');
    })
}

export const showInterstitialAd = ()=>{
    
    if (GameData.LevelData && GameData.LevelData.passNum <= GameTileStaticJsonData.InterstitialAd.startLevel){
        return;
    }
    closeWindowCount++;
    CCLog.log("关闭窗口次数", closeWindowCount, "总次数",GameTileStaticJsonData.InterstitialAd.closeWindowCount)
    if (closeWindowCount >= GameTileStaticJsonData.InterstitialAd.closeWindowCount){
        closeWindowCount = 0;
        JsbTileTrileTileCallMgr.handler('showInterstitialAd');
    }
}